<?php

namespace App\Http\Middleware;

use Closure;
use App\Traits\ApiResponsable;
use App\Models\User;
use App\Services\LoginUser;

class Auth
{
    use ApiResponsable;

    /**
     * @var User
     */
    protected $user;

    /**
     * Create a new middleware instance.
     *
     * @return void
     */
    public function __construct(LoginUser $loginUser)
    {
        $this->user = $loginUser->user;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $route = $request->route();
        // 获取当前操作的函数文档注释
        if (isset($route['1']['uses'])) {
            $uses = explode('@', $route['1']['uses']);
            $action = new \ReflectionMethod($uses[0], $uses[1]);
            $doc = $action->getDocComment();
            // 从注释中找出权限限制
            if (preg_match('/@auth\(([\d,]*)\)/', $doc, $matches)) {
                $roles = explode(',', $matches[1]);
                // 确认是否登录
                if ($this->user === null) {
                    return $this->error('您未登录系统或已退出');
                }
                // 判断当前用户是否有权限
                if (!in_array($this->user->role, $roles)) {
                    return $this->error('您没有权限执行此操作');
                }
            } // 如果没有写@auth则按照公共接口处理

            return $next($request);
        } else {
            return $this->error('系统错误请联系管理员');
        }
    }
}
